let oss = require('./oss');
let fs = require('fs');
let path = require('path');
let debug = require('debug')('file2oss:file2oss');

module.exports = class file2oss {
    constructor(ossclient, options) {
        if (!ossclient || !(ossclient instanceof oss)) {
            throw '请选择OSSClient';
        }
        this.OSS = ossclient;
        this.file = {
            directory: options.directory,
            path: path.join(options.directory, options.relpath),
            relpath: options.relpath,
            name: path.basename(options.relpath)
        }
    }

    /**
     * 发送文件
     * @return {Promise<void>}
     */
    async send() {
        let filepath = oss.parsePath(this.file.relpath);
        let rts = await this.OSS.putStream(filepath, fs.createReadStream(this.file.path));
        return rts;
    }

    /**
     * 验证oss文件是否跟本地文件大小一样
     * @return {Promise<boolean>}
     */
    async valid() {
        let filepath = oss.parsePath(this.file.relpath);
        let rts = await this.OSS.head(filepath);
        let stat = fs.statSync(this.file.path);
        return rts.res.headers['content-length'] === stat.size.toString()
    }


    /**
     * 删除本地文件
     * @return {Promise<void>}
     */
    delete() {
        fs.unlinkSync(this.file.path);
    }


    async deleteRemote() {
        throw '未完成功能';
    }

    async down() {
        throw '未完成功能';
    }

    async content() {
        return fs.readFileSync(this.file.path, {encoding: 'utf8'});
    }

    async contentRemote() {
        throw '未完成功能';
    }

    /**
     * windows下转换文件路径
     * @param filepath
     * @returns {string}
     */
    static parsePath(filepath) {
        return path.sep === '\\' ? filepath.split(path.sep).join('/') : filepath;
    }
};